<template>
  <div class="app-container">
    <div class="top">
      <div>
        <img src="../assets/images/deviceInfoTitle.png" alt="" />
      </div>
      <div>备件入库</div>
    </div>
    <div class="container">
      <div class="search">
        <div class="search-buttons">
          <el-button v-hasPermi="['deviceIn:deviceIn:add']" type="primary" size="mini" @click="addInData">新增</el-button>
          <el-button size="mini" @click="importData" v-hasPermi="['deviceIn:deviceIn:import']">导入</el-button>
          <el-button size="mini" @click="exportData" v-hasPermi="['deviceIn:deviceIn:export']">导出</el-button>
        </div>
        <div class="search-form">
          <el-form :model="queryParams" ref="queryForm" size="small" :inline="true">
            <el-form-item label="单号" prop="orderNo">
              <el-input v-model="queryParams.orderNo" placeholder="请输入" clearable @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="仓库名称" prop="warehouseName">
              <el-input v-model="queryParams.warehouseName" placeholder="请输入" clearable
                @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="提交人" prop="submitUserName">
              <el-input v-model="queryParams.submitUserName" placeholder="请输入" clearable
                @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select v-model="queryParams.status">
                <el-option v-for="value in typeList" :value="value.id" :key="value.id" :label="value.name"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="时间">
              <el-date-picker v-model="dateRange" style="width: 240px" value-format="yyyy-MM-dd" type="daterange"
                range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" size="mini" @click="handleQuery">查询</el-button>
              <el-button size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <el-divider></el-divider>
      <div class="table-container">
        <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
          <!-- <el-table-column label="单号" align="center" prop="orderNo" min-width="170"
                        :show-overflow-tooltip="true">
                        <template slot-scope="scope">
                            <div class="specialTitle">{{ scope.row.orderNo }}</div>
                        </template>
</el-table-column> -->
  <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="单号" align="center" prop="orderNo" min-width="170" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <!-- 触发 popover 的元素 -->
              <el-popover placement="top" width="800" trigger="click" @show="getOrderDetail(scope.row)">
                <!-- 自定义弹窗内容 -->
                <div class="order-popover">
                  <el-table stripe :data="stockInFo.stockInDetails" style="width: 100%" ref="previewTable">
                    <el-table-column label="序号" width="50" align="center">
                      <template slot-scope="scope">{{
                        scope.$index + 1
                      }}</template>
                    </el-table-column>
                    <el-table-column label="备件名称" prop="partName" min-width="120" align="center"
                      :show-overflow-tooltip="true"></el-table-column>
                    <el-table-column label="编码" prop="partCode" min-width="120" align="center"
                      :show-overflow-tooltip="true"></el-table-column>
                    <el-table-column label="型号" :show-overflow-tooltip="true" prop="specModel" align="center"
                      min-width="120"></el-table-column>
                    <el-table-column label="单位" prop="unit" align="center"
                      :show-overflow-tooltip="true"></el-table-column>
                    <el-table-column label="数量" align="center" prop="quantity">
                      <template slot-scope="scope">{{
                        Number(scope.row.quantity)
                      }}</template>
                    </el-table-column>
                    <el-table-column label="单价/元" align="center">
                      <template slot-scope="scope">{{
                        Number(scope.row.unitPrice)
                      }}</template>
                    </el-table-column>

                    <el-table-column label="总价/元" align="center">
                      <template slot-scope="scope">
                        {{
                          Number(scope.row.unitPrice || 0) *
                          Number(scope.row.quantity || 0)
                        }}
                      </template>
                    </el-table-column>
                  </el-table>
                </div>

                <!-- 表格里真正显示的“单号” -->
                <span slot="reference" class="specialTitle click-text">
                  {{ scope.row.orderNo }}
                </span>
              </el-popover>
            </template>
          </el-table-column>

          <el-table-column label="仓库名称" align="center" prop="warehouseName" min-width="150"
            :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <div class="specialTitle">{{ scope.row.warehouseName }}</div>
            </template>
          </el-table-column>

          <el-table-column label="提交日期" align="center" prop="submitDate" min-width="160"
            :show-overflow-tooltip="true" />
          <el-table-column label="入库日期" align="center" prop="inDate" min-width="160" :show-overflow-tooltip="true" />
          <el-table-column label="提交人" align="center" prop="submitUserName" min-width="100"
            :show-overflow-tooltip="true" />
          <el-table-column label="入库人" align="center" prop="inUserName" min-width="100" :show-overflow-tooltip="true" />
          <el-table-column label="入库总额/元" align="center" prop="totalAmount" min-width="100"
            :show-overflow-tooltip="true" />
          <el-table-column label="状态" align="center" prop="status" min-width="80" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <!-- <div v-if="scope.row.status == '0'" style="color: #FF851D;">待提交</div> -->
              <div v-if="scope.row.status == '1'" style="color: green">
                已提交
              </div>
              <div v-if="scope.row.status == '2'" style="color: #1f90ff">
                草稿
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="100" class-name="small-padding fixed-width" fixed="right">
            <template slot-scope="scope">
              <el-button size="mini" type="text" v-hasPermi="['deviceIn:deviceIn:view']"
                @click="handleView(scope.row)">查看</el-button>
              <el-button size="mini" type="text" v-if="scope.row.status == '2'" @click="handleUpdate(scope.row)"
                v-hasPermi="['deviceIn:deviceIn:edit']">编辑</el-button>
              <el-button v-if="scope.row.status == '0'" size="mini" type="text" @click="handleSubmit(scope.row)"
                v-hasPermi="['deviceIn:deviceIn:submit']">提交</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getList" />
    </div>

    <el-dialog title="详情" :visible.sync="open" width="900px" append-to-body>
      <div style="height: 70vh; overflow-y: auto">
        <div class="summary-card" ref="summaryCard">
          <div class="summary-row">
            <div class="summary-item">
              <span class="label">单号：</span>
              <span class="value">{{ stockInFo.orderNo }} </span>
            </div>
            <div class="summary-item">
              <span class="label">仓库：</span>
              <span class="value">{{
                stockInFo.warehouseName || stockInFo.warehouseCode || "-"
              }}</span>
            </div>
            <div class="summary-item">
              <span class="label">总金额：</span>
              <span class="value">{{ stockInFo.totalAmount }} 元</span>
            </div>
          </div>
          <div class="summary-row">
            <div class="summary-item">
              <span class="label">提交人：</span>
              <span class="value">{{ stockInFo.submitUserName || "-" }}</span>
            </div>
            <div class="summary-item">
              <span class="label">入库人：</span>
              <span class="value">{{ stockInFo.inUserName || "-" }}</span>
            </div>
            <div class="summary-item">
              <span class="label">提交时间：</span>
              <span class="value">{{ stockInFo.submitDate || "-" }}</span>
            </div>
          </div>
        </div>
        <el-table stripe :data="stockInFo.stockInDetails" style="width: 100%" ref="previewTable">
          <el-table-column label="序号" width="50" align="center">
            <template slot-scope="scope">{{ scope.$index + 1 }}</template>
          </el-table-column>
          <el-table-column label="备件名称" prop="partName" align="center"></el-table-column>
          <el-table-column label="编码" prop="partCode" align="center"></el-table-column>
          <el-table-column label="型号" :show-overflow-tooltip="true" prop="specModel" align="center"></el-table-column>
          <el-table-column label="单位" prop="unit" align="center"></el-table-column>
          <el-table-column label="数量" align="center" prop="quantity">
            <template slot-scope="scope">{{
              Number(scope.row.quantity)
            }}</template>
          </el-table-column>
          <el-table-column label="单价/元" align="center">
            <template slot-scope="scope">{{
              Number(scope.row.unitPrice)
            }}</template>
          </el-table-column>

          <el-table-column label="总价/元" align="center">
            <template slot-scope="scope">
              {{
                Number(scope.row.unitPrice || 0) *
                Number(scope.row.quantity || 0)
              }}
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>

    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url"
        :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess"
        :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <!-- <div class="el-upload__tip" slot="tip">
            <el-checkbox
              v-model="upload.updateSupport"
            />是否更新已经存在的数据
          </div> -->
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline"
            @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { listoutPut, submitoutPut, getoutPut } from "@/api/deviceIn.js";
import { getToken } from "@/utils/auth";
export default {
  name: "deviceInfo",
  data() {
    return {
       ids:[],
      // 日期范围
      dateRange: [],
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        // updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/outPut/in/importData",
      },
      open: false,
      stockInFo: {},
      typeList: [
        // {
        //     id: 0,
        //     name: '待提交'
        // },
        {
          id: 1,
          name: "已提交",
        },
        {
          id: 2,
          name: "草稿",
        },
      ],
      userList: [],
      loading: false,
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderNo: undefined,
        submitUserName: undefined,
        warehouseName: undefined,
        status: undefined,
        params: {
          beginTime: '',
          endTime: ''
        }
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 下载模板操作 */
    importTemplate() {
      this.download(
        "/outPut/in/importTemplate",
        {},
        `入库导入模版_${new Date().getTime()}.xlsx`
      );
    },
    importData() {
      this.upload.title = "备件入库导入";
      this.upload.open = true;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
        response.msg +
        "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      const file = this.$refs.upload.uploadFiles;
      if (
        !file ||
        file.length === 0 ||
        (!file[0].name.toLowerCase().endsWith(".xls") &&
          !file[0].name.toLowerCase().endsWith(".xlsx"))
      ) {
        this.$modal.msgError("请选择后缀为 “xls”或“xlsx”的文件。");
        return;
      }
      this.$refs.upload.submit();
    },
    getOrderDetail(row) {
      getoutPut(row.stockInId).then((res) => {
        this.stockInFo = res.data;
      });
    },
    handleView(row) {
      getoutPut(row.stockInId).then((res) => {
        this.stockInFo = res.data;
        this.open = true;
      });
    },
    handleSubmit(row) {
      row.status = 1;
      this.$modal
        .confirm("是否确认提交此数据？")
        .then(function () {
          return submitoutPut(row);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("提交成功");
        })
        .catch(() => { });
    },
    handleUpdate(row) {
      this.$router.push({
        path: "/addDeviceIn/index",
        query: {
          type: "edit",
          stockInId: row.stockInId,
        },
      });
    },
    addInData() {
      this.$router.push({
        path: "/addDeviceIn/index",
        query: {
          type: "add",
        },
      });
    },
     handleSelectionChange(selection) {
      this.ids = selection.map(item => item.stockInId)
    },
    /** 查询参数列表 */
    getList() {
      this.loading = true;
      listoutPut(this.addDateRange(this.queryParams, this.dateRange)).then((response) => {
        this.userList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 表单重置
    reset() {
      this.form = {
        orderNo: undefined,
        submitUserName: undefined,
        warehouseName: undefined,
        status: undefined,
      };
      this.resetForm("form");
    },
    /** 查询按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    exportData() {
      this.queryParams.params.beginTime= this.dateRange[0]
      this.queryParams.params.endTime= this.dateRange[1]
      this.queryParams.ids= this.ids
      this.download('outPut/in/export', {
        ...this.queryParams
       
      }, `入库明细_${new Date().getTime()}.xlsx`)
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm("queryForm");
      this.handleQuery();
    },
  },
};
</script>
<style scoped lang="scss">
.app-container {
  width: 100%;
  height: calc(100vh - 60px);
  display: flex;
  flex-direction: column;
  overflow: hidden;
  padding-bottom: 10px;
}

.container {
  width: 100%;
  margin-top: 16px;
  background: #fff;
  padding: 24px 24px 0px 24px;
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;

  .el-divider {
    margin: 20px 0 !important;
  }

  .search {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 16px;
    justify-content: space-between;

    .search-buttons {
      flex-shrink: 0;
    }

    .search-form {
      flex: 1;
      min-width: 0;
      display: flex;
      justify-content: flex-end;

      /* 让表单内容靠右 */
      ::v-deep .el-form {
        display: flex;
        flex-wrap: wrap;
        align-items: center;
        gap: 16px;
        margin: 0;
        padding: 0;
        // justify-content: flex-end;
      }

      ::v-deep .el-form-item {
        margin: 0;
        flex-shrink: 0;
      }

      ::v-deep .el-input {
        width: 160px;
        height: 32px;
        line-height: 32px;
      }

      ::v-deep .el-form-item__label {
        font-family: PingFang SC;
        font-weight: 400;
        font-size: 14px;
        height: 32px;
        line-height: 32px;
        letter-spacing: 0%;
        vertical-align: middle;
        color: #313d4b;
      }
    }
  }

  .table-container {
    flex: 1;
    overflow: auto;
  }
}

.top {
  width: 100%;
  height: 56px;
  border-radius: 4px;
  background: rgba(255, 255, 255, 1);
  display: flex;
  align-items: center;
  padding: 0 16px;

  >div:first-child {
    width: 24px;
    height: 24px;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative; // 新增

    img {
      width: 100%;
      height: 100%;
      object-fit: contain;
      position: relative;
      top: 2px; // 微调图片垂直位置
    }
  }

  >div:last-child {
    font-family: PingFang SC;
    margin-left: 8px;
    font-weight: 500;
    font-size: 18px;
    color: rgba(29, 33, 41, 1);
    line-height: 24px;
    height: 24px;
    display: flex;
    align-items: center;
  }
}

.specialTitle {
  font-family: PingFang SC;
  font-weight: 400;
  font-style: Regular;
  font-size: 14px;
  color: #41a772;
}

.summary-card {
  width: 100%;
  background: #f5f7fa;
  border-radius: 4px;
  padding: 16px;
  margin-bottom: 16px;

  .summary-row {
    display: flex;
    flex-wrap: wrap;
    gap: 20px 100px;
    margin-bottom: 20px;

    &:last-child {
      margin-bottom: 0;
    }
  }

  .summary-item {
    display: flex;
    align-items: center;
    min-width: 200px;

    .label {
      color: #4e5969;
      font-size: 14px;
      margin-right: 8px;
    }

    .value {
      color: #1d2129;
      font-weight: 500;
      font-size: 14px;
    }
  }
}
</style>
